package com.carrot.uaa.infrastructure.redis;

import com.carrot.uaa.constant.Oauth2Constants;
import com.carrot.uaa.util.RedisUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Component
@RequiredArgsConstructor
public class RedisTokenUtils {

    private final RedisOperator<Object> redisOperator;

    /**
     * 删除用户同一个客户端的其他令牌，目的是实现同一个端只有一个在线帐号
     * @param onLineTokenKey
     * @param clientId
     */
    public void delOtherOnlineToken(String onLineTokenKey,String clientId){
        if(redisOperator.hseKey(onLineTokenKey)){
            Map<String,String> otherOnLinToken = (Map<String, String>) redisOperator.
                    getHash(onLineTokenKey, clientId);
            if(otherOnLinToken!=null){
                String otherLineRefreshToken= RedisUtils
                        .getUserOnLineRefreshTokenKey(otherOnLinToken.get(Oauth2Constants.REFRESH_TOKEN));
                String otherLineAccessToken=RedisUtils
                        .getUserOnLineAccessTokenKey(otherOnLinToken.get(Oauth2Constants.ACCESS_TOKEN));
                redisOperator.delete(otherLineRefreshToken,otherLineAccessToken);
            }
        }
    }

    /**
     * 撤销令牌
     * @param revokeToken
     * @param refreshToken
     * @param accessToken
     */
    public void revokeToken(String revokeToken,String refreshToken,String accessToken){
        String onLineAccessTokenKey= RedisUtils.getUserOnLineAccessTokenKey(accessToken);
        String onLineRefreshTokenKey= RedisUtils.getUserOnLineRefreshTokenKey(refreshToken);
        //撤销访问令牌，仅下线访问令牌
        if(accessToken.equals(revokeToken)){
            redisOperator.delete(onLineAccessTokenKey);
        }
        //撤销刷新令牌，则下线访问令牌和刷新令牌
        if(refreshToken!=null&&refreshToken.equals(revokeToken)){
            redisOperator.delete(onLineAccessTokenKey,onLineRefreshTokenKey);
        }

    }

    /**
     * 保存访问令牌
     * @param key
     * @param value
     * @param exp
     */
    public void saveAccessToken(String key,Object value,Long exp){
        redisOperator.set(key,value,exp);
    }

    /**
     * 保存刷新令牌
     * @param key
     * @param value
     * @param exp
     */
    public void saveRefreshToken(String key,Object value,Long exp){
        redisOperator.set(key,value,exp);
    }


    /**
     * 保存令牌
     * @param key
     * @param client
     * @param value
     * @param exp
     */
    public void saveToken(String key,String client,Object value,Long exp){
        redisOperator.setHash(key,client,value);
        redisOperator.expire(key,exp, TimeUnit.SECONDS);
    }



}
